<template>
  <div class="app-container">
    <div class="app-container-flex">
      <div class="left-container">
        <div class="left-container-header border-style-bottom">
          <!-- 维修组树 -->
          <div v-for="item in btnList.beforeList" :key="item.value">
            <el-button
              v-if="item.value === 'add'"
              :plain="true"
              @click="addGroup"
              >新增</el-button
            >
            <el-button
              v-if="item.value === 'delGroup'"
              :plain="true"
              :disabled="!canDelete"
              @click="delGroup"
              >删除</el-button
            >
          </div>
        </div>
        <div class="left-container-header">
          <el-input
            v-model="groupInfo.query.nameLike"
            style="flex: 1; margin-right: 10px"
            :clearable="true"
            placeholder="请输入名称"
            @keyup.enter="init"
          ></el-input>
          <el-button @click="init">搜索</el-button>
        </div>
        <p class="slip-edit group-p">维修组信息</p>
        <div class="left-container-main main-flex">
          <div style="overflow: auto; margin-left: 20px">
            <div style="width: 283px">
              <p
                @click="getUserList"
                :class="
                  clickUserAll ? 'group-item-click group-item' : 'group-item'
                "
              >
                全部维修人员
              </p>
              <div
                v-for="(item, index) in groupInfo.data"
                :key="index"
                style="width: 100%; display: inline-block"
              >
                <p
                  @click="getDetail(item)"
                  :class="
                    clickRow.id === item.id
                      ? 'group-item-click group-item'
                      : 'group-item'
                  "
                >
                  {{ item.name }}
                </p>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="right-container">
        <div v-if="showDeptSubmitBox" class="layui-card-body">
          <!-- 基础信息 -->
          <div class="layui-btn-container border-style-bottom">
            <el-button :plain="true" :disabled="saveBtn" @click="updateGroup">
              保存
            </el-button>
          </div>
          <div>
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="groupFormInfo.ref"
              :data="groupFormInfo.data"
              :field-list="groupFormInfo.fieldList"
              :rules="groupFormInfo.rules"
              :label-width="groupFormInfo.labelWidth"
            >
              <template v-slot:form-resourceList>
                <span class="slip-edit" @click="updateResource">资源</span>
              </template>
            </page-form>
          </div>
        </div>
        <!-- 用户 -->
        <div class="layui-card-body">
          <div class="opt-header border-style-bottom">
            <page-filter
              v-model:query="filterInfo.query"
              :filter-list="filterInfo.list"
            >
              <template v-slot:filter-addUser>
                <el-button :disabled="currentDeptId <= 0" @click="addUser"
                  >新增</el-button
                >
              </template>
              <template v-slot:filter-btnDelete>
                <el-button
                  :disabled="!tableInfo.selections.length"
                  @click="del()"
                  >删除</el-button
                >
              </template>
            </page-filter>
          </div>
          <p class="slip-edit group-p" style="padding-left: 10px">
            维修成员信息
          </p>
          <table-container
            :refresh="tableInfo.refresh"
            :init-curpage="tableInfo.initCurpage"
            v-model:data="tableInfo.data"
            :api="tableInfo.api"
            :query="filterInfo.query"
            :field-list="tableInfo.fieldList"
            :handle="tableInfo.handle"
            @handleEvent="handleEvent"
          >
          </table-container>
        </div>
      </div>

      <!---新增维修组--->
      <page-dialog
        v-if="modifyInfo.visible"
        :title="modifyInfo.title"
        v-model:visible="modifyInfo.visible"
        :width="modifyInfo.width"
        :bt-list="modifyInfo.btList"
      >
        <page-form
          class="paddingBox order-model-formBox flex_wrap_start_start"
          v-model:ref-obj.sync="addGroupFormInfo.ref"
          :data="addGroupFormInfo.data"
          :field-list="addGroupFormInfo.modifyFieldList"
          :rules="addGroupFormInfo.rules"
          :label-width="addGroupFormInfo.labelWidth"
        >
          <template v-slot:form-resourceList>
            <span class="slip-edit" @click="addResource">资源</span>
          </template>
        </page-form>
      </page-dialog>
    </div>

    <Resource
      v-if="resourceInfo.visible"
      v-model:show-dialog="resourceInfo.visible"
      :id="resourceInfo.id"
      :data="resourceInfo.data"
      @callback="resourceCallback"
    />
    <!-- 选择用户 -->
    <select-no-auth-users
      v-if="selectUserInfo.visible"
      v-model:showDialog="selectUserInfo.visible"
      :query="selectUserInfo.query"
      :api="getRrgUserList"
      :saveEmpty="true"
      :check-box="true"
      :highlight-row="true"
      @callback="selectUserCallBack"
    />
  </div>
</template>

<script setup name="maintenanceGroup">
import SelectNoAuthUsers from '@/components/SelectUsers/selectNoAuthUsers'
import TableContainer from '@/components/TableContainer/index'
import PageForm from '@/components/PageForm/index'
import PageFilter from '@/components/PageFilter/index'
import PageDialog from '@/components/PageDialog/index'

import { getRrgUserList } from '@/api/base'
import {
  deleteMaintenanceGroupUser,
  getMaintenanceGroupAll,
  createMaintenanceGroup,
  updateMaintenanceGroup,
  getMaintenanceGroupById,
  getMaintenanceGroupUserPage,
  deleteMaintenanceGroupById,
  batchInsertMaintenanceGroupUser,
  updateMaintenanceGroupUser,
} from '@/api/repair'
import Resource from './resource'
const { proxy } = getCurrentInstance()
const emit = defineEmits()
const clickUserAll = ref(false)
const clickRow = ref({})
const canNotAddUser = ref(true)
const currentDeptId = ref(0)
const UserBox = ref(true)
const showDeptSubmitBox = ref(false)
const addBtn = ref(true) //控制左侧树节点上方新增按钮状态
const saveBtn = ref(true)
const resourceInfo = reactive({
  //资源弹窗
  visible: false,
  id: '',
  data: [],
})
const selectUserInfo = reactive({
  visible: false,
  saveEmpty: true,
  query: {
    // type:"normal"
    idNotIn: '',
  },
})
const btnList = reactive({
  beforeList: [
    {
      value: 'add',
    },
    {
      value: 'delGroup',
    },
  ],
})
// 维修组列表
const groupInfo = reactive({
  data: [],
  query: {
    nameLike: '',
  },
})
const addGroupFormInfo = ref({
  ref: null,
  data: {
    repairPartsRequired: '0',
  },
  labelWidth: '140px',
  fieldList: [
    {
      label: '维修组名称',
      value: 'name',
      type: 'input',
    },
    {
      label: '维修组编码',
      value: 'code',
      type: 'input',
      maxlength: 50,
    },
    {
      label: '维修配件是否必填',
      value: 'repairPartsRequired',
      type: 'select-model',
      code: 'repair_parts_required',
    },
    { label: '资源', value: 'resourceList', type: 'slot' },
  ],
  modifyFieldList: [
    {
      label: '维修组名称',
      value: 'name',
      type: 'input',
    },
    {
      label: '维修组编码',
      value: 'code',
      type: 'input',
      maxlength: 50,
    },
    {
      label: '维修配件是否必填',
      value: 'repairPartsRequired',
      type: 'select-model',
      code: 'repair_parts_required',
    },
    { label: '资源', value: 'resourceList', type: 'slot' },
  ],
  rules: {
    code: [
      { required: true, message: '请输入维修组编码', trigger: 'blur' },
      { validator: proxy.$validate.validatEn, trigger: 'blur' },
    ],
    name: [{ required: true, message: '请输入维修组名称', trigger: 'blur' }],
  },
})

//新增维修组弹窗表单
const groupFormInfo = reactive({
  ref: null,
  data: {
    repairPartsRequired: '0',
  },
  labelWidth: '140px',
  fieldList: [
    {
      label: '维修组名称',
      value: 'name',
      type: 'input',
    },
    {
      label: '维修组编码',
      value: 'code',
      type: 'input',
      maxlength: 50,
    },
    {
      label: '维修配件是否必填',
      value: 'repairPartsRequired',
      type: 'select-model',
      code: 'repair_parts_required',
    },
    { label: '资源', value: 'resourceList', type: 'slot' },
  ],
  modifyFieldList: [
    {
      label: '维修组名称',
      value: 'name',
      type: 'input',
    },
    {
      label: '维修组编码',
      value: 'code',
      type: 'input',
      maxlength: 50,
    },
    {
      label: '维修配件是否必填',
      value: 'repairPartsRequired',
      type: 'select-model',
      code: 'repair_parts_required',
    },
    { label: '资源', value: 'resourceList', type: 'slot' },
  ],
  rules: {
    code: [
      { required: true, message: '请输入维修组编码', trigger: 'blur' },
      { validator: proxy.$validate.validatEn, trigger: 'blur' },
    ],
    name: [{ required: true, message: '请输入维修组名称', trigger: 'blur' }],
  },
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    sort: 'create_time desc',
    groupId: '',
  },
  list: [
    { type: 'slot', value: 'addUser', label: '新增' },
    { type: 'slot', value: 'btnDelete', label: '删除' },
    {
      type: 'input',
      label: '工号/姓名',
      clearable: true,
      value: 'keyword',
      event: search,
    },
    { type: 'button', label: '搜索', event: search },
  ],
})
// 表格相关
const tableInfo = reactive({
  selections: [],
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: getMaintenanceGroupUserPage,
  fieldList: [
    {
      label: '工号',
      value: 'userName',
    },
    { label: '姓名', value: 'name' },
    { label: '维修组', value: 'groupName' },
    { label: '联系电话', value: 'tel' },
    { label: '可接单状态', value: 'statusValue' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '更改状态',
        event: changeStatus,
        show: true,
      },
    ],
  },
})

const modifyInfo = reactive({
  visible: false,
  title: '添加维修组',
  width: '60%',
  btLoading: false,
  btList: [
    {
      label: '关闭',
      type: '',
      icon: '',
      event: closeModify,
      show: true,
    },
    {
      label: '保存',
      type: 'primary',
      icon: '',
      event: createGroup,
      saveLoading: false,
      show: true,
    },
  ],
})

const canDelete = computed(() => {
  return groupInfo.data.length && clickRow.value && clickRow.value.id
})

onMounted(() => {
  init()
})

function changeStatus(row) {
  //更改状态
  row.status = row.status === 1 ? 0 : 1
  updateMaintenanceGroupUser(row).then((res) => {
    if (res && res.success) {
      loadUserList(clickRow.value.id)
    }
  })
}
function getUserList() {
  //获取维修人员
  showDeptSubmitBox.value = false
  clickRow.value = {}
  clickUserAll.value = true
  currentDeptId.value = 0
  tableInfo.selections = []
  loadUserList()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    // 对表格获取到的数据做处理
    case 'tableCheck':
      tableInfo.selections = data
      break
  }
}

// 加载数据
function init() {
  getMaintenanceGroupAll(groupInfo.query).then((res) => {
    if (res.success) {
      groupInfo.data = res.data
    }
  })
  getUserList()
}
function getTreeItem(data, param) {
  data.forEach((item) => {
    if (item.children && item.children.length) {
      getTreeItem(item.children, param)
    }
    if (item.id.toString() === param.deptId) {
      handleNodeClick(item)
      return
    } else if (item.id === param.id) {
      handleNodeClick(item)
      proxy.$nextTick(function () {
        proxy.$refs.menuTree.setCurrentKey(item.id)
      })
      return
    }
  })
}

function closeModify() {
  modifyInfo.visible = false
}
//删除维修组
function delGroup() {
  deleteMaintenanceGroupById(clickRow.value.id).then((resp) => {
    if (resp && resp.success) {
      init()
    }
  })
}
// 获取维修信息
function getGroupDetail(node) {
  getMaintenanceGroupById(node.id).then((res) => {
    groupFormInfo.data = {
      ...res.data,
    }
  })
}
// 加载当前维修组下用户列表
function loadUserList(id = '') {
  filterInfo.query.groupId = id
  proxy.$nextTick(function () {
    tableInfo.refresh = Math.random()
  })
}
// 点击树节点
function getDetail(node) {
  clickUserAll.value = false
  clickRow.value = node
  addBtn.value = false

  currentDeptId.value = node.id || 0
  if (node.id > 0) {
    saveBtn.value = false
    // 获取部门信息和部门内人员列表
    getGroupDetail(node)
    UserBox.value = true
    showDeptSubmitBox.value = true
    loadUserList(node.id)
  } else {
    groupFormInfo.data = {}
    showDeptSubmitBox.value = false
    saveBtn.value = true
    UserBox.value = true
    loadUserList()
  }
  setTimeout(() => {
    proxy.$store.dispatch('app/toggleOpenFilter')
  }, 0)
}
// 新增用户或编辑
function addUser() {
  selectUserInfo.query.idNotIn = tableInfo.data
    .map((item) => item.userId)
    .toString()
  selectUserInfo.visible = true
}

function search() {
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}

function createGroup() {
  //添加维修组
  addGroupFormInfo.value.ref.validate((valid) => {
    if (valid) {
      createMaintenanceGroup(addGroupFormInfo.value.data).then((res) => {
        if (res && res.success) {
          modifyInfo.visible = false
          init()
        }
      })
    }
  })
}
// 更新维修组
function updateGroup() {
  groupFormInfo.ref.validate((valid) => {
    if (valid) {
      updateMaintenanceGroup(groupFormInfo.data).then((res) => {
        if (res && res.success) {
          init()
          getDetail(groupFormInfo.data)
        }
      })
    }
  })
}
//添加维修组
function addGroup() {
  addGroupFormInfo.value.data = {}
  modifyInfo.visible = true
}
function resourceCallback(data) {
  //选择资源返回
  if (resourceInfo.id) {
    groupFormInfo.data.resourceList = data.map((item) => {
      item.groupId = groupFormInfo.data.id
      return item
    })
  } else {
    addGroupFormInfo.value.data.resourceList = data.map((item) => {
      return item
    })
  }
}
function selectUserCallBack(data) {
  //选择用户返回
  if (data.length) {
    let params = data.map((item) => {
      item.groupId = groupFormInfo.data.id
      item.userId = item.id
      return item
    })
    batchInsertMaintenanceGroupUser(params).then((res) => {
      if (res && res.success) {
        loadUserList(groupFormInfo.data.id)
      }
    })
  }
}
function del() {
  //删除维修成员
  proxy
    .$confirm('删除后将改变数据,是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    .then(() => {
      let ids = tableInfo.selections.map((row) => row.id)
      deleteMaintenanceGroupUser(ids).then((resp) => {
        if (resp && resp.success) {
          loadUserList(groupFormInfo.data.id)
        }
      })
    })
}

function addResource() {
  //新增资源
  resourceInfo.id = ''
  resourceInfo.visible = true
  resourceInfo.data = addGroupFormInfo.value.data.resourceList
}
function updateResource() {
  //修改资源
  resourceInfo.id = groupFormInfo.data.id
  resourceInfo.visible = true
  resourceInfo.data = groupFormInfo.data.resourceList
}
</script>

<style lang="scss" scoped>
.app-container {
  height: calc(100vh - 83px);
}
.left-container {
  min-width: 320px;
  .left-container-header {
    display: flex;
    align-items: center;
    //justify-content: space-around;
  }
}
.main-flex {
  flex-grow: 1;
  display: flex;
  flex-wrap: nowrap;
  height: calc(100% - 240px);
  .el-tree {
    width: 100%;
    padding: 0 20px 20px;
    overflow-y: auto;
    :deep(.el-tree-node__children) {
      overflow: initial;
    }
  }
}

.group-item {
  height: 26px;
  line-height: 26px;
  cursor: pointer;
  display: inline-block;
  width: 91%;
  padding-left: 10px;
  white-space: nowrap;
  outline: 0;
}
.group-item:hover {
  background-color: #f5f7fa;
}
.group-item-click {
  background-color: #e6f0f5;
}
.group-p {
  font-size: 14px;
  font-weight: 600;
  padding-bottom: 10px;
  padding-left: 20px;
}
</style>
